package com.fingard.csp.listener;

import com.fingard.csp.service.socket.SocketMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Socket侦听服务
 *
 * @author fanghh
 * @version v1.0.1
 * @date 2021.7.20
 */
@Slf4j
@Component
public class SocketServerListener implements ServletContextListener {
    public SocketServerThread socketServerThread;

    @Autowired
    public Environment env;

    @Autowired
    public SocketMessageService socketMsgService;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        if (socketServerThread == null) {
            socketServerThread = new SocketServerThread(env, socketMsgService);
            socketServerThread.start();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        if (socketServerThread != null && !socketServerThread.isInterrupted()) {
            socketServerThread.closeSocketServer();
            socketServerThread.interrupt();
        }
    }
}